package ar.edu.itba.pod.legajo45129;

import java.rmi.registry.Registry;
import java.util.StringTokenizer;

import com.google.inject.internal.Preconditions;

public class NodeId {
	private String ip;
	private int port;
	private static final String TOKEN = ":";
	
	public NodeId(String nodeId) {
		Preconditions.checkNotNull(nodeId);
//		System.out.println(nodeId);
		StringTokenizer st = new StringTokenizer(nodeId, TOKEN);
		
		this.ip = st.nextToken();
//		Preconditions.checkArgument("127.0.0.1".equals(nodeId) == false);
//		Preconditions.checkArgument("localhost".equals(nodeId) == false);
		
		if (st.hasMoreElements()) {
			this.port = Integer.parseInt(st.nextToken());
		} else {
			this.port = Registry.REGISTRY_PORT;
		}
	}

	public String getIp() {
		return ip;
	}

	public void setIp(String ip) {
		this.ip = ip;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((ip == null) ? 0 : ip.hashCode());
		result = prime * result + port;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (obj == null) {
			return false;
		}
		
		if (obj instanceof NodeId) {
			NodeId other = (NodeId) obj;
			return this.ip.equals(other.getIp()) && this.port == other.getPort();
		}
		
		if (obj instanceof String) {
			return this.equals(new NodeId((String)obj));
		}
		
		return false;
	}
	
	@Override
	public String toString() {
//		return this.ip + ":" + this.port;
		return this.ip;
	}
}
